package com.rimi.shiro;

import com.rimi.bean.YqzcUser;
import com.rimi.model.dto.LoginDto;
import com.rimi.service.UserService;
import com.rimi.util.JwtUtil;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * @Author luc
 * @Date 2021/7/2
 */
public class BearerRealm extends MysqlRealm {


    @Autowired
    UserService userService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof BearerToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String bearer=(String) token.getPrincipal();

        try {
            LoginDto decode= JwtUtil.decode(LoginDto.class,bearer);

            if (decode!=null){
                //获取过期时间
                Date exp=decode.getExp();
                if (System.currentTimeMillis()<=exp.getTime()){
                    YqzcUser yqzcUser=userService.findUserById(decode.getId());

                    if (yqzcUser!=null){
                        return new SimpleAuthenticationInfo(yqzcUser,null,getName());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

       throw new AuthenticationException("token效验失败");
    }

    @Override
    protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {

    }
}
